package personal.wang.dic;


import personal.wang.utils.TemplateAnalyseUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

import static personal.wang.utils.TemplateAnalyseUtils.extractVar;


/**
 * 词典类， 包含了dictioinaries目录下的词典文件中的词典数据 词典都是有命名空间的，如果不指定命名空间，则默认为default命名空间
 * 
 * @author
 *
 */
public class Dictionary {
	private Map<String, Properties> dics = new HashMap<>();
	private Dictionary(){}
	private static ThreadLocal<Dictionary> local = new ThreadLocal<>();
	public static class DictionarySingleton{
		public static Dictionary getInstance(){
			Dictionary dictionary = local.get();
			if(Objects.isNull(dictionary)){
				local.set(new Dictionary());
			}
			return local.get();
		}
	}
	public void addDic(String namespace, Properties dic) {
		Properties d = dics.get(namespace);
		if (d == null) {
			d = new Properties();
			dics.put(namespace, d);
		}
		d.putAll(dic);
	}

	public void addDic(Properties dic) {
		addDic("default", dic);
	}

	public void addDic(String namespace, String key, String value) {
		Properties d = dics.get(namespace);
		if (d == null) {
			d = new Properties();
			dics.put(namespace, d);
		}
		d.put(key, value);
	}

	public void addDic(String key, String value) {
		addDic("default", key, value);
	}

	public String getDicVal(String namespace, String key) {
		Properties d = dics.get(namespace);
		if (d == null) {
			return null;
		}
		String property = d.getProperty(key);
		if(Objects.isNull(property)){
			throw new RuntimeException(key + " is not in ditionary");
		}
		String rs = null ;
		// 处理枚举中有函数的情况。
		if(property.contains("$Var{") || property.contains("$Func{")){
				Map<String, String> stringStringMap = extractVar(property);
			Map<String, String> execute = null;
			try {
				execute = TemplateAnalyseUtils.execute(stringStringMap);
			} catch (Exception e) {
				e.printStackTrace();
			}
			rs = TemplateAnalyseUtils.replace(property,execute);
		}else{
			rs = d.getProperty(key);
		}
		return rs;
	}

	public String getDicStr(String key) {
		return getDicVal("default", key);
	}

	public String[] getDicArray(String key) {
		return getDicVal("default", key) == null ? null : getDicVal("default", key).split("\\|\\|\\|");
	}
}
